const { ipcRenderer } = require("electron");
const { exec } = require('child_process');
const osu = require('../common/cdn/node-os-utils/index.js');
window.ipcRenderer = ipcRenderer;
window.osu = osu;
window.alwaysOnTop = () => {
  ipcRenderer.sendTo(window.senderId, "win", "alwaysOnTop");
  let data = window.getData()
  window.sendSaveData(data)
};

window.isAlwaysOnTop = () => {
  ipcRenderer.sendTo(window.senderId, "win", "isAlwaysOnTop");
};

window.getPosition = () => {
  ipcRenderer.sendTo(window.senderId, "win", "position");
};

window.moveDirection = (type, num) => {
  ipcRenderer.sendTo(window.senderId, "direction", {type, num});
}

window.sendSaveData = (data) => {
  ipcRenderer.sendTo(window.senderId, "saveData", data);
};

ipcRenderer.on("senderId", (event) => {
  window.senderId = event.senderId;
});

window.closeWin = () => {
  if(window.closeSettingWin){
    window.closeSettingWin()
  }
  ipcRenderer.sendTo(window.senderId, "win", "close");
};

// 向父页面传送数据
window.toParentPage = (data, info) => {
  ipcRenderer.sendTo(window.senderId, 'toParent', {data, ...info});
}



window.getNetworkStats = () => {
  return new Promise((resolve, reject) => {
    exec('netstat -e', (err, stdout, stderr) => {
      if (err) {
        return reject(err);
      }
      const lines = stdout.split('\n');
      const stats = lines[4].trim().split(/\s+/);
      const rxBytes = parseInt(stats[1], 10) / 4; // Received bytes
      const txBytes = parseInt(stats[2], 10) / 4; // Sent bytes
      resolve({ rxBytes, txBytes });
    });
  });
}

window.calculateSpeed = (previousData, currentData, interval) => {
    const rxBytesPerSec = (currentData.rxBytes - previousData.rxBytes) / interval;
  const txBytesPerSec = (currentData.txBytes - previousData.txBytes) / interval;
  return { rxBytesPerSec, txBytesPerSec };
}

